package grammar.parser.stmt;

import error.processing.MyErrorProcessing;
import exp.parser.Exp;
import word.parser.WordElement;

public class ReturnStmt extends Stmt {
    private final Exp exp;

    public ReturnStmt() {
        exp = null;
    }

    public ReturnStmt(Exp exp) {
        this.exp = exp;
    }

    public static ReturnStmt buildReturnStmt() {
        assert getAnalyzingWord().getType() == WordElement.WordType.RETURNTK;
        int returnPosition = getNowPosition();
        analyzeNextWord();
        ReturnStmt returnStmt;
        if (Exp.isExpPrefix(getAnalyzingWord())) {
            returnStmt = new ReturnStmt(Exp.buildExp());
            if (!MyErrorProcessing.isHaveReturn()) {
                MyErrorProcessing.buildErrorProcessing(MyErrorProcessing.ErrorType.f,
                        getWord(returnPosition));
            }
        } else {
            returnStmt = new ReturnStmt();
            if (MyErrorProcessing.isHaveReturn()) {
                MyErrorProcessing.buildErrorProcessing(MyErrorProcessing.ErrorType.g, getWord(returnPosition));
            }
        }

        if (getAnalyzingWord().getType() != WordElement.WordType.SEMICN) {
            MyErrorProcessing.buildErrorProcessing(MyErrorProcessing.ErrorType.i, getAnalyzingWord(-1));
        } else {
            analyzeNextWord();
        }

        return returnStmt;
    }

    public Exp getExp() {
        return exp;
    }

    @Override
    public void execute() {

        Integer ans = null;
        if (exp != null) {
            ans = exp.getValue();
        }
        // System.out.println("return" + ans);
        getSemanticParser().callReturn();
        getSemanticParser().setReVal(ans);
    }
}
